package com.qiqu.controller;

import com.qiqu.Vo.UsersVo;
import com.qiqu.commen.Const;
import com.qiqu.entity.Users;
import com.qiqu.service.UsersService;
import com.qiqu.utils.AuthUtil;
import com.qiqu.utils.JSONResult;
import com.qiqu.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("users")
@Api(value = "用户相关接口",tags = {"用户相关接口controller"})
public class UsersController {
    @Resource
    private UsersService usersService;
    @Resource
    private RedisOperator redisOperator;

    //修改个人信息
    @ApiOperation(value = "用户个人信息修改--fk",notes = "用户个人信息修改")
    @PostMapping("/updatePersonInfo")
    public JSONResult updatePersonInfo(@RequestBody Users user){
        usersService.updateUser(user);
        return new JSONResult(JSONResult.ok());
    }


    //用户注册与获取基本信息
    @ApiOperation(value = "用户注册与获取基本信息--fk",notes = "用户注册与获取基本信息")
    @GetMapping("/register")
    public JSONResult register(String faceImage,String code,String nickname) throws IOException {
        //首先判断是否存在该用户，如果存在直接返回信息，否则注册再返回信息
        Users user = new Users();
        user.setFaceImage(faceImage);
        user.setNickname(nickname);
        //根据code获取唯一的微信openId
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxb6cc718c583b3bb2&secret=798e638e29005ef6c17ce42df58b7b4a&js_code="+code+"&grant_type=authorization_cod";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        String openid = jsonObject.getString("openid");
        user.setWeixin(openid);
        UsersVo user1 =new UsersVo();
        Users user2 = usersService.queryByWx(user.getWeixin());
        if(user2==null){
            user.setFaceImages(1);
            usersService.insert(user);
            user2=usersService.queryByWx(user.getWeixin());
        }
        //System.out.println(user2);
        String str = Const.USER_REDIS_SESSION+":"+user2.getId();
        String getToken = redisOperator.get(str);
        if(getToken==null){
            String token= UUID.randomUUID().toString();
            redisOperator.set( str,token,Const.TOKEN_AGE);
            getToken=token;
        }
        BeanUtils.copyProperties(user2, user1);
        user1.setToken(getToken);
        return new JSONResult(JSONResult.ok(user1));
    }

    //上传头像
    @ApiOperation(value = "用户头像上传--fk",notes = "用户头像上传接口")
    @ApiImplicitParam(name="userId",value = "用户Id",required = true, dataType = "string",paramType = "query")
    @PostMapping(value = {"/uploadFace"},headers = "content-type=multipart/form-data")
    public JSONResult uploadFace(String userId,
                                 @ApiParam(value = "用户头像",required = true)
                                         MultipartFile file) throws IOException {
        if(StringUtils.isBlank(userId)){
            return JSONResult.errorMsg("用户Id不能为空...");
        }
        //文件保存路径
        String fileSpace= Const.FILE_SPACE;
        //数据库保存路径
        String uploadPathDB = "/rbook/"+userId+"/face";
        FileOutputStream fileOutputStream =null;
        InputStream inputStream=null;
        try{
            if(file !=null){
                //获取文件名
                String fileName=file.getOriginalFilename();
                if(StringUtils.isNotBlank(fileName)){
                    //文件上传的最终路径
                    String finalFacePath = fileSpace + uploadPathDB +"/"+fileName;
                    //设置数据库保存路径
                    uploadPathDB +="/"+fileName;
                    File outFile = new File(finalFacePath);
                    if(outFile.getParentFile()!=null || outFile.getParentFile().isDirectory()){
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream,fileOutputStream);
                }
            }else {
                return JSONResult.errorMsg("上传出错...");
            }
        }catch (Exception e){
            e.printStackTrace();
            return JSONResult.errorMsg("上传出错...");
        }finally {
            if(fileOutputStream !=null){
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        Users user=new Users();
        user.setId(userId);
        user.setFaceImages(2);
        user.setFaceImage(uploadPathDB);
        usersService.updateUserFace(user);
        return JSONResult.ok(uploadPathDB);
    }

    @ApiOperation(value = "获取用户信息--fk",notes = "获取用户信息")
    @ApiImplicitParam(name="userId",value = "用户Id",required = true, dataType = "string",paramType = "query")
    @GetMapping("getUserInfo")
    public JSONResult getUserInfo(String userId){
        return JSONResult.ok(usersService.queryById(userId));
    }


}
